import React,{useState,useEffect}from 'react'
import './less/Menas.less'
import { Button, Form, Input ,message, Upload} from 'antd';
import {GetUserDataApi,ChangeUserDataApi}from '../request/api'
// import { triggerFocus } from 'antd/lib/input/Input';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';


const getBase64 = (img, callback) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
};

const beforeUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';

  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
  }

  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }

  return isJpgOrPng && isLt2M;
};


export default function Means() {
  const [username1,setUsername1]=useState('')
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState();

  const handleChange = (info) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }

    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, (url) => {
        setLoading(false);
        setImageUrl(url);
        localStorage.setItem('avatar',info.file.response.data.filePath)
      });
    }
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div
        style={{
          marginTop: 8,
        }}
      >
        Upload
      </div>
    </div>
  );

  useEffect(()=>{
    GetUserDataApi().then(res=>{
      console.log(res);
      setUsername1(res.data.username)
      // setAvatar(res.data.avatar)
      if(res.errCode===0){
        message.success(res.message)
        //存到sessionStorage
        sessionStorage.setItem('username',res.data.username)
      }
    })
  },[])
  const onFinish = (values) => {
    console.log('Success:', values);
    if(values.username&&values.username!==sessionStorage.getItem('username')&&values.password!=='null'){
      ChangeUserDataApi({
        username:values.username,
        password:values.password
      }).then(res=>{
        // console.log(res);
        if(res.errCode===0){
          message.success(res.message)
        }else{
          message.error(res.message)
        }
      })
    }
  };

  // const onFinishFailed = (errorInfo) => {
  //   console.log('Failed:', errorInfo);
  // };
  return (
    <div className='means'>
       <Form
       style={{width:'400px'}}
      name="basic"
    
      labelCol={{
        span: 8,
      }}
      wrapperCol={{
        span: 16,
      }}
      // initialValues={{
      //   username:username1,
      //   password:password1
      // }}
      onFinish={onFinish}
      // onFinishFailed={onFinishFailed}
      autoComplete="off"
    >
      <Form.Item
        label="修改用户名"
        name="username"
        rules={[
          {
            required: true,
            message: 'Please input your username!',
          },
        ]}
      >
        <Input placeholder={username1} />
      </Form.Item>

      <Form.Item
        label="修改密码"
        name="password"
        rules={[
          {
            required: true,
            message: 'Please input your password!',
          },
        ]}
      >
        <Input.Password />
      </Form.Item>
      <Form.Item
        wrapperCol={{
          offset: 8,
          span: 16,
        }}
      >
        <Button type="primary" htmlType="submit">
         提交修改
        </Button>
      </Form.Item>
    </Form>

    <Upload
      name="avatar"
      listType="picture-card"
      className="avatar-uploader"
      showUploadList={false}
      action="/api/uploader"
      beforeUpload={beforeUpload}
      onChange={handleChange}
      headers={{"cms-token":localStorage.getItem('cms-token')}}
    >
      {imageUrl ? (
        <img
          src={imageUrl}
          alt="avatar"
          style={{
            width: '100%',
          }}
        />
      ) : (
        uploadButton
      )}
    </Upload>
    </div>
  )
}
